package com.ruoyi.project.dentalOrder.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ijpay.core.kit.WxPayKit;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.websocket.WebSocketUsers;
import com.ruoyi.project.baoxiu.card.service.IOrderWarrantyCardService;
import com.ruoyi.project.baoxiu.moban.service.IWarrantyCardService;
import com.ruoyi.project.dentalOrder.domain.DentalOrder;
import com.ruoyi.project.dentalOrder.domain.ProductItem;
import com.ruoyi.project.dentalOrder.service.IDentalOrderService;
import com.ruoyi.project.orderWorks.domain.OrderWorks;
import com.ruoyi.project.orderWorks.service.IOrderWorksService;
import com.ruoyi.project.product.product.service.IProductService;
import com.ruoyi.project.product.sku.domain.ProductSku;
import com.ruoyi.project.product.sku.service.IProductSkuService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 产品订单Controller
 * 
 * @author wyh
 * @date 2024-08-20
 */
@RestController
@RequestMapping("/dentalOrder/dentalOrder/api")
public class DentalOrderApiController extends BaseController
{
    @Autowired
    private IDentalOrderService dentalOrderService;

    @Autowired
    private IOrderWorksService orderWorksService;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IOrderWarrantyCardService orderWarrantyCardService;

    @Autowired
    private IWarrantyCardService warrantyCardService;

    /**
     * 查询我的订单
     */
    @GetMapping("/test")
    public void test()
    {
        System.out.println("实时通讯");
        String message = "您有一个新订单";
        WebSocketUsers.sendMessageToUserByText("1", message);
    }

    /**
     * 查询我的订单
     */
    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:list')")
    @GetMapping("/myOrders")
    public TableDataInfo myOrders(DentalOrder dentalOrder)
    {
        Long userId = SecurityUtils.getUserId();
        dentalOrder.setUserId(userId);

        startPage();
        List<DentalOrder> list = dentalOrderService.selectDentalOrderList(dentalOrder);
        return getDataTable(list);
    }

    /**
     * 查询产品订单列表
     */
    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(DentalOrder dentalOrder)
    {
        startPage();
        List<DentalOrder> list = dentalOrderService.selectDentalOrderList(dentalOrder);
        return getDataTable(list);
    }

    /**
     * 获取产品订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:query')")
    @GetMapping(value = "/{outTradeNo}")
    public AjaxResult getInfo(@PathVariable("outTradeNo") String outTradeNo)
    {
        Long userId = SecurityUtils.getUserId();
        DentalOrder dentalOrder = dentalOrderService.selectDentalOrderByOutTradeNo(outTradeNo);
        if(ObjectUtils.isEmpty(dentalOrder)){
            return AjaxResult.error("订单不存在");
        }
        if(!dentalOrder.getUserId().equals(userId)){
            return AjaxResult.error("订单不属于当前用户");
        }
        return success(dentalOrder);
    }

    /**
     * 新增产品订单
     */
    @Log(title = "产品订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DentalOrder dentalOrder)
    {
        System.out.println("新增产品订单++++");
        System.out.println(dentalOrder);

        //校验支付类型
        String payType = dentalOrder.getPayType();
        if(StringUtils.isBlank(payType)){
            return error("支付类型不能为空");
        }

        //获取用户信息
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        BigDecimal balance = sysUser.getBalance();//用户余额

        //获取订单信息
        List<ProductItem> fixedClassProducts = dentalOrder.getFixedClassList();//固定类
        List<ProductItem> activityClassProducts = dentalOrder.getActivityClassList();//活动类
        List<ProductItem> paiClassProducts = dentalOrder.getPaiClassList();//排牙

        //判断产品是否都为空
        if(fixedClassProducts==null && activityClassProducts==null && paiClassProducts==null){
            return error("产品不能为空");
        }

        //产品总价值
        BigDecimal totalPrice = BigDecimal.ZERO;

        //固定类
        if(fixedClassProducts!=null && fixedClassProducts.size()>0){
            for(ProductItem item:fixedClassProducts){
                Long productId = item.getProductId();

                //校验产品id
                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
                Long skuProductId = productSku.getProductId();
                if(!productId.equals(skuProductId)){
                    return error("产品id和sku产品id不一致");
                }

                BigDecimal price = productSku.getPrice();
                Long num = item.getNum();

                if(null == num){
                    return error("产品数量不能为空");
                }

                BigDecimal multiply = price.multiply(new BigDecimal(num));
                totalPrice = totalPrice.add(multiply);

            }
        }

        //计算产品价格
        if(activityClassProducts!=null && activityClassProducts.size()>0){
            for(ProductItem item:activityClassProducts){
                Long productId = item.getProductId();

                //校验产品id
                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
                Long skuProductId = productSku.getProductId();
                if(!productId.equals(skuProductId)){
                    return error("产品id和sku产品id不一致");
                }

                BigDecimal price = productSku.getPrice();
                Long num = item.getNum();

                if(null == num){
                    return error("产品数量不能为空");
                }

                BigDecimal multiply = price.multiply(new BigDecimal(num));
                totalPrice = totalPrice.add(multiply);

            }
        }

        if(paiClassProducts!=null && paiClassProducts.size()>0){
            for(ProductItem item:paiClassProducts){
                Long productId = item.getProductId();

                //校验产品id
                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
                Long skuProductId = productSku.getProductId();
                if(!productId.equals(skuProductId)){
                    return error("产品id和sku产品id不一致");
                }

                BigDecimal price = productSku.getPrice();
                Long num = item.getNum();

                if(null == num){
                    return error("产品数量不能为空");
                }

                BigDecimal multiply = price.multiply(new BigDecimal(num));
                totalPrice = totalPrice.add(multiply);

            }
        }


        //支付方式为余额支付 校验是否余额充足
        if("余额支付".equals(payType)){
            if(totalPrice.compareTo(balance)>0){
                return error("余额不足");
            }else{
                dentalOrder.setBalancePayAmount(totalPrice);//余额支付价格

                dentalOrder.setScorePayAmount(0L);

                //扣除余额
                BigDecimal yuE = balance.subtract(totalPrice);
                sysUser.setBalance(yuE);
                userService.updateUser2(sysUser);
            }
        }else if("混合支付".equals(payType)){
            Long scorePayAmount = dentalOrder.getScorePayAmount();

            //判断积分是否充足
            Long score = sysUser.getScore();
            if(score<scorePayAmount){
                return error("积分不足");
            }

            //判断积分是否大于订单金额20%
            BigDecimal scorePay = new BigDecimal(scorePayAmount);
            BigDecimal twentyPercentOfTotalPrice = totalPrice.multiply(new BigDecimal("0.2"));
            if (scorePay.compareTo(twentyPercentOfTotalPrice) > 0) {
                return error("积分支付金额不能大于订单金额的20%");
            }

            BigDecimal otherPay = totalPrice.subtract(scorePay);//总价减去积分付款

            //余额支付加个是否大于余额
            if(otherPay.compareTo(balance)>0){
                return error("余额不足");
            }

            dentalOrder.setBalancePayAmount(otherPay);//余额支付价格

            //更新账户余额
            BigDecimal newBalance = balance.subtract(otherPay);
            score = score - scorePayAmount;
            sysUser.setScore(score);
            sysUser.setBalance(newBalance);
            userService.updateUser2(sysUser);
        }else{
            return error("支付类型必须是 '余额支付' 或 '混合支付'");
        }

        //创建订单
        dentalOrder.setStatus("已付款");
        dentalOrder.setUserId(userId);
        String outTradeNo = WxPayKit.generateStr();//订单编号
        dentalOrder.setOutTradeNo(outTradeNo);

        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将列表转换为 JSON 字符串
            String fixedClassJson = objectMapper.writeValueAsString(dentalOrder.getFixedClassList());
            dentalOrder.setFixedClass(fixedClassJson);

            String activityClass = objectMapper.writeValueAsString(dentalOrder.getActivityClassList());
            dentalOrder.setActivityClass(activityClass);

            String paiClass = objectMapper.writeValueAsString(dentalOrder.getPaiClassList());
            dentalOrder.setPaiClass(paiClass);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        dentalOrder.setTotalAmount(totalPrice);

        //查询保修卡模板
//        WarrantyCard warrantyCard = warrantyCardService.selectWarrantyCardById(1L);
//
//        //添加保修卡
//        if(ObjectUtils.isNotEmpty(fixedClassProducts)){
//
//            for(ProductItem item:fixedClassProducts){
//                OrderWarrantyCard card = new OrderWarrantyCard();
//                card.setProductId(item.getProductId());
//                card.setOutTradeNo(outTradeNo);
//                card.setUserId(userId);
//                card.setContent(warrantyCard.getContent());
//                orderWarrantyCardService.insertOrderWarrantyCard(card);
//            }
//
//        }
//
//        if(ObjectUtils.isNotEmpty(activityClassProducts)){
//
//            for(ProductItem item:activityClassProducts){
//                OrderWarrantyCard card = new OrderWarrantyCard();
//                card.setProductId(item.getProductId());
//                card.setOutTradeNo(outTradeNo);
//                card.setUserId(userId);
//                card.setContent(warrantyCard.getContent());
//                orderWarrantyCardService.insertOrderWarrantyCard(card);
//            }
//
//        }
//
//        if(ObjectUtils.isNotEmpty(paiClassProducts)){
//
//            for(ProductItem item:paiClassProducts){
//                OrderWarrantyCard card = new OrderWarrantyCard();
//                card.setProductId(item.getProductId());
//                card.setOutTradeNo(outTradeNo);
//                card.setUserId(userId);
//                card.setContent(warrantyCard.getContent());
//                orderWarrantyCardService.insertOrderWarrantyCard(card);
//            }
//
//        }

        //给流程部门发送通知
        List<SysUser> sysUsers = dentalOrderService.queryWorkers();
        for (SysUser w:sysUsers) {
            Long userId1 = w.getUserId();
            WebSocketUsers.sendMessageToUserByText(""+userId1+"", "您有一个新订单");

            //创建流程记录
            OrderWorks orderWorks = new OrderWorks();
            orderWorks.setUserId(userId1);
            orderWorks.setOutTradeNo(outTradeNo);
            orderWorks.setStatus("待处理");
            orderWorks.setDeptId(w.getDeptId());
            orderWorksService.insertOrderWorks(orderWorks);
        }

        return toAjax(dentalOrderService.insertDentalOrder(dentalOrder));
    }

//    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:add')")
//    @Log(title = "产品订单", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody DentalOrder dentalOrder)
//    {
//        System.out.println("新增产品订单++++");
//        System.out.println(dentalOrder);
//
//        //校验支付类型
//        String payType = dentalOrder.getPayType();
//        if(StringUtils.isBlank(payType)){
//            return error("支付类型不能为空");
//        }
//
//        //获取用户信息
//        Long userId = SecurityUtils.getUserId();
//        SysUser sysUser = userService.selectUserById(userId);
//        BigDecimal balance = sysUser.getBalance();//用户余额
//
//        //获取订单信息
//        String fixedClass = dentalOrder.getFixedClass();//固定类
//        String activityClass = dentalOrder.getActivityClass();//活动类
//        String paiClass = dentalOrder.getPaiClass();//排牙
//
//        //判断产品是否都为空
//        boolean allEmpty = areAllClassesEmpty(fixedClass, activityClass, paiClass);
//        if (allEmpty) {
//            return error("固定类、活动类和排牙至少有一项不为空");
//        }
//
//        //转换json
//        List<ProductItem> fixedClassProducts = parseJsonStringToProductList(fixedClass);
//        List<ProductItem> activityClassProducts = parseJsonStringToProductList(activityClass);
//        List<ProductItem> paiClassProducts = parseJsonStringToProductList(paiClass);
//
//        //产品总价值
//        BigDecimal totalPrice = null;
//
//        //固定类
//        if(fixedClassProducts!=null && fixedClassProducts.size()>0){
//            for(ProductItem item:fixedClassProducts){
//                Long productId = item.getProductId();
//
//                //校验产品id
//                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
//                Long skuProductId = productSku.getProductId();
//                if(!productId.equals(skuProductId)){
//                    return error("产品id和sku产品id不一致");
//                }
//
//                BigDecimal price = productSku.getPrice();
//                Long num = item.getNum();
//
//                if(null == num){
//                    return error("产品数量不能为空");
//                }
//
//                BigDecimal multiply = price.multiply(new BigDecimal(num));
//                totalPrice.add(multiply);
//
//            }
//        }
//
//        //计算产品价格
//        if(activityClassProducts!=null && activityClassProducts.size()>0){
//            for(ProductItem item:activityClassProducts){
//                Long productId = item.getProductId();
//
//                //校验产品id
//                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
//                Long skuProductId = productSku.getProductId();
//                if(!productId.equals(skuProductId)){
//                    return error("产品id和sku产品id不一致");
//                }
//
//                BigDecimal price = productSku.getPrice();
//                Long num = item.getNum();
//
//                if(null == num){
//                    return error("产品数量不能为空");
//                }
//
//                BigDecimal multiply = price.multiply(new BigDecimal(num));
//                totalPrice.add(multiply);
//
//            }
//        }
//
//        if(paiClassProducts!=null && paiClassProducts.size()>0){
//            for(ProductItem item:paiClassProducts){
//                Long productId = item.getProductId();
//
//                //校验产品id
//                ProductSku productSku = productSkuService.selectProductSkuById(item.getSkuId());
//                Long skuProductId = productSku.getProductId();
//                if(!productId.equals(skuProductId)){
//                    return error("产品id和sku产品id不一致");
//                }
//
//                BigDecimal price = productSku.getPrice();
//                Long num = item.getNum();
//
//                if(null == num){
//                    return error("产品数量不能为空");
//                }
//
//                BigDecimal multiply = price.multiply(new BigDecimal(num));
//                totalPrice.add(multiply);
//
//            }
//        }
//
//        //支付方式为余额支付 校验是否余额充足
//        if("余额支付".equals(payType)){
//            if(totalPrice.compareTo(balance)>0){
//                return error("余额不足");
//            }else{
//                dentalOrder.setBalancePayAmount(totalPrice);//余额支付价格
//
//                //扣除余额
//                BigDecimal yuE = balance.subtract(totalPrice);
//                sysUser.setBalance(yuE);
//                userService.updateUser2(sysUser);
//            }
//        }else if("混合支付".equals(payType)){
//            Long scorePayAmount = dentalOrder.getScorePayAmount();
//
//            //判断积分是否充足
//            Long score = sysUser.getScore();
//            if(score<scorePayAmount){
//                return error("积分不足");
//            }
//
//            //判断积分是否大于订单金额20%
//            BigDecimal scorePay = new BigDecimal(scorePayAmount);
//            BigDecimal twentyPercentOfTotalPrice = totalPrice.multiply(new BigDecimal("0.2"));
//            if (scorePay.compareTo(twentyPercentOfTotalPrice) > 0) {
//                return error("积分支付金额不能大于订单金额的20%");
//            }
//
//            BigDecimal otherPay = totalPrice.subtract(scorePay);//总价减去积分付款
//            dentalOrder.setBalancePayAmount(otherPay);//余额支付价格
//
//            //更新账户余额
//            BigDecimal newBalance = balance.subtract(otherPay);
//            score = score - scorePayAmount;
//            sysUser.setScore(score);
//            sysUser.setBalance(newBalance);
//            userService.updateUser2(sysUser);
//        }else{
//            return error("支付类型必须是 '余额支付' 或 '混合支付'");
//        }
//
//        //创建订单
//        dentalOrder.setStatus("已付款");
//        dentalOrder.setUserId(userId);
//        String outTradeNo = WxPayKit.generateStr();//订单编号
//        dentalOrder.setOutTradeNo(outTradeNo);
//
//        return toAjax(dentalOrderService.insertDentalOrder(dentalOrder));
//    }

    /**
     * 修改产品订单
     */
    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:edit')")
    @Log(title = "产品订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DentalOrder dentalOrder)
    {
        return toAjax(dentalOrderService.updateDentalOrder(dentalOrder));
    }

    /**
     * 删除产品订单
     */
    @PreAuthorize("@ss.hasPermi('dentalOrder:dentalOrder:remove')")
    @Log(title = "产品订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{outTradeNos}")
    public AjaxResult remove(@PathVariable String[] outTradeNos)
    {
        return toAjax(dentalOrderService.deleteDentalOrderByOutTradeNos(outTradeNos));
    }

    /**
     * 校验订单产品是否都为空
     * @param fixedClass
     * @param activityClass
     * @param paiClass
     * @return
     */
    public static boolean areAllClassesEmpty(String fixedClass, String activityClass, String paiClass) {
        return (fixedClass == null || fixedClass.isEmpty()) &&
                (activityClass == null || activityClass.isEmpty()) &&
                (paiClass == null || paiClass.isEmpty());
    }

    /**
     * json转换
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static List<ProductItem> parseJsonStringToProductList(String jsonString) {
        try {
            if (jsonString == null || jsonString.isEmpty()) {
                return new ArrayList<>(); // 返回空列表
            }
            return objectMapper.readValue(jsonString, new TypeReference<List<ProductItem>>(){});
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>(); // 如果解析失败，返回空列表
        }
    }
}
